package net2;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.HashMap;

public class UdpDictServer {

    private static HashMap<String, String> dict;
    private static final int PORT = 4090;

    public static void main(String[] args) throws IOException {
        iniDict();
        System.out.println("服务器启动...");
        DatagramSocket socket = new DatagramSocket(PORT);
        while (true) {
            System.out.println("正在等待接收客户端请求...");
            byte[] req = new byte[128];
            DatagramPacket request = new DatagramPacket(req, req.length);
            socket.receive(request);
            System.out.println("已收到客户端" + request.getSocketAddress() + "请求，开始处理...");
            String getBytes = new String(request.getData());
            char[] chars = getBytes.toCharArray();
            StringBuilder stringBuilder = new StringBuilder();
            for (char aChar : chars) {
                if (aChar == '.') {
                    break;
                } else {
                    stringBuilder.append(aChar);
                }
            }
            getBytes = stringBuilder.toString();

            String resp = dict.getOrDefault(getBytes, "没有找到翻译");
            byte[] bytes = resp.getBytes();
            DatagramPacket response =
                    new DatagramPacket(bytes, bytes.length, request.getSocketAddress());
            socket.send(response);
            System.out.println("已向客户端返回响应...");
            System.out.println("------------------");
        }
    }

    private static void iniDict () {
        dict = new HashMap<>();
        dict.put("Matty", "李育鸿");
        dict.put("Justin", "比伯");
        dict.put("Stephen", "库里");
    }

}
